///*
// * Copyright (c) 2006-2021, RT-Thread Development Team
// *
// * SPDX-License-Identifier: Apache-2.0
// *
// * Change Logs:
// * Date           Author       Notes
// * 2023-07-03     18421       the first version
// */
#include "commandparse.h"
//#include "cJSON.h"
#include "stdlib.h"
#include "stdio.h"
#include "dev_4gmodule.h"
#include "ota.h"
#include "switch.h"
#include "stdio.h"

#define THREAD_PRIORITY         25
#define THREAD_TIMESLICE        5
static rt_thread_t recvParseThread;

static struct recvData recvdate={0};




//static void* (*cmdModeCfgRecvCallback)(uint8_t mode) = NULL;
//static void* (*cmdStatusInitCfgRecvCallback)()=NULL;
//static void* (*cmdOtaDataRecvCallback)() = NULL;
//static void* (*cmdAdressCfgCallback)(const char * ip,const char *port) =NULL;

/**
 *收到数据回调函数
 */
static void mqtt_recv_cb(const char* topicName, const char * data, rt_uint16_t dataLength)
{
    rt_mutex_take(recvdate.recvDataMutex, RT_WAITING_FOREVER);

    rt_memset(recvdate.recvDataBuff,0,512);
    rt_memset(recvdate.topic, 0, 128);
    rt_memcpy(recvdate.recvDataBuff, data, dataLength);
    rt_memcpy(recvdate.topic, topicName, rt_strlen(topicName));
    recvdate.recvDataLen=dataLength;

    rt_mutex_release(recvdate.recvDataMutex);
    rt_sem_release(recvdate.recvDataSem);
}



//{"data":{"SwitchState":0,"CtrlPort":2},"id":"8"}
static void cmdDownParse(char *topic, const char* jsondata, uint16_t datasz)
{
    int ctrlport,swstatus;
    char* pos;
    char id[20]={0};


    pos=rt_strstr(jsondata, "SwitchState");
    if(pos)
    {
        sscanf(pos,"SwitchState\":%d",&swstatus);
    }
    pos=rt_strstr(jsondata, "CtrlPort");
    {
        sscanf(pos,"CtrlPort\":%d",&ctrlport);
    }

    pos = rt_strstr(jsondata, "id");
    {
        int idLen=0,p = 5;

        while(pos[p]!='"' && idLen<20)
        {

            id[idLen++]=pos[p++];
        }
    }
    netCmdCtrl(ctrlport-1,swstatus,id);

}

static void prodSercetDownParse(const char* jsondata, uint16_t datasz)
{
//{"token": "776ffb980041490699e0067ad6b82a93"}
    if (air724x_mqtt_DevSercet_status() != RT_EOK)
    {
        char buff[33] = { 0 };
        char *pos;
        pos = rt_strstr(jsondata, "deviceSecret");
        if (pos)
        {

            rt_memcpy(buff, pos + 15, 32);
            air724x_mqtt_set_devSercet(buff);
        }
    }

}

static void otaInfoParse(const char * data, uint16_t datasz)
{
    //在mqttx软件测试，发现mqtt消息会发生两次，ota消息会发送两次

//    {"data":{"size":84944,"module":"0.0.6","sign":"fff2ae18cde1b29ef22879518953b175","id":"1688372348621","version":"0.0.1",
    //"url":"http://iot.yun.gdatacloud.com:32664/api/http/event/downLoad/3321","signMethod":"MD5"},"id":"1688372348621"}

    //old
//    {"id":"1657624304163","data":{"size":25908,"module":"mcu","sign":"ba3a591a38d5ab4f45ca57c319f0c880",
//    "id":"1657624304163","version":"30","url":"http://o.d.gdatacloud.com/api/http/event/downLoad/3275","signMethod":"MD5"}}
    typeofDownloadInfo_t info;
    info=ota_get_info_struct();
    char *pos ;
    uint8_t p=0;
    uint32_t tmp = 0;

    pos = rt_strstr(data, "version");
    if (pos)
    {
        p = 0;
        tmp = 0;
        otaversion_t otaversin;
        sscanf(pos, "version\":\"%d.%d.%d", &otaversin.ota_MajorVersion, &otaversin.ota_ChildVersion, &otaversin.ota_ReVision);
        tmp = otaVersinToint(&otaversin);
//        pos += 10; //指向第一个数
//        while (pos[p] != '\"' && p < datasz)
//        {
//            tmp = tmp * 10 + (pos[p++] - '0');
//        }

        if (info->ota_VersionNumber == tmp)
            return;
        info->ota_VersionNumber = tmp;
    }
    pos = rt_strstr(data, "size");
    if (pos)
    {
        p=0;
        tmp = 0;
        pos+=6;
        while (pos[p] != ',' && p < datasz)
        {
            tmp = tmp * 10 + (pos[p++] - '0');
        }
        info->ota_size=tmp;
    }

    pos = rt_strstr(data, "sign");
    if (pos)
    {
        rt_memcpy(info->ota_crc,pos+7,32);
    }

    pos = rt_strstr(data, "url");
    if (pos)
    {
        uint8_t i=0;
        char *posend;
        posend=rt_strstr(pos, "com");
        posend+=3;
        rt_memcpy(info->ota_url, pos+13, posend-pos-13); //过滤掉http://


        pos=posend+1;
        while (pos[i] != '/' && i < 6)
        {
            info->ota_port[i]=pos[i];
            i++;
        }
        pos=pos+i;
        i=0;
        while (pos[i] != '\"' && i < 128)
        {
            info->ota_route[i] = pos[i];
            i++;
        }
    }
    pos = rt_strstr(data, "id");
    {
        int idLen = 0;
        p = 5;
        rt_memset(info->id, 0, 20);
        while (pos[p] != '"' && idLen < 20)
        {

            info->id[idLen++] = pos[p++];
        }
    }
    rt_kprintf("id()url(%s)port(%s)route(%s)\n", info->ota_url,info->ota_port, info->ota_route);

    ota_notify();

}


static void recvParseEntry(void *parameter)
{

    static rt_err_t result;
    while (1)
    {
        /* 永久方式等待信号量，获取到信号量 */
        rt_sem_take(recvdate.recvDataSem, RT_WAITING_FOREVER);
        result=rt_mutex_take(recvdate.recvDataMutex, 0);

        if (result == RT_EOK)
        {
            if (rt_strstr(recvdate.topic, CMD_DOWN_TOPIC_HEAD)) //命令下发
            {
                rt_kprintf("[commandParse]%s\n",recvdate.recvDataBuff);
                cmdDownParse(recvdate.topic,recvdate.recvDataBuff,recvdate.recvDataLen);
            }
            else if(rt_strstr(recvdate.topic, "/ext/register"))
            {
                //productSercet下发
                rt_kprintf("[commandParse]%s\n",recvdate.recvDataBuff);

                prodSercetDownParse(recvdate.recvDataBuff,recvdate.recvDataLen);

            }
            else if(rt_strstr(recvdate.topic, OTA_DOWN_TOPIC_HEAD)&&(rt_strstr(recvdate.topic,OTA_DOWN_TOPIC_PARAMETERS)))
            {
                //ota信息解析
                rt_kprintf("[commandParse.ota]%s\n",recvdate.recvDataBuff);

                otaInfoParse(recvdate.recvDataBuff,recvdate.recvDataLen);
            }
            rt_thread_mdelay(1001);

        }
        rt_mutex_release(recvdate.recvDataMutex);

    }
}

int recvParseInit(void)
{
    /* 创建一个动态互斥量 */
    recvdate.recvDataMutex = rt_mutex_create("recMutex", RT_IPC_FLAG_FIFO);
    recvdate.recvDataSem = rt_sem_create("recSem", 0, RT_IPC_FLAG_FIFO);

    recvParseThread=rt_thread_create("recPar", recvParseEntry, NULL, 1024+256, 14, THREAD_TIMESLICE);
    MQTT_SetRevCallback(mqtt_recv_cb);
    if(recvParseThread==NULL || recvdate.recvDataSem==NULL ||recvdate.recvDataMutex==NULL)
    {
        rt_kprintf("[cmdParse]recvParesthread init fail");
        return 1;
    }
    rt_thread_startup(recvParseThread);
    rt_kprintf("[cmdParse]recvParesthread init ok\n");
    return 0;
}
INIT_APP_EXPORT(recvParseInit);
